// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"

// 物理页总数
#define PGTOL (PHYSTOP - KERNBASE) / PGSIZE
// 根据物理地址索引页编号
#define PA2ID(pa) (((pa) - KERNBASE) / PGSIZE)
// 保存每个索引页的引用计数
int pg_refs[PGTOL];
// 访问引用计数数组的互斥锁 
struct spinlock pg_refs_lock;

void freerange(void *pa_start, void *pa_end);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct {
  struct spinlock lock;
  struct run *freelist;
} kmem;

void
kinit()
{
  initlock(&kmem.lock, "kmem");
  // 初始化引用锁
  initlock(&pg_refs_lock, "pgrefs"); 
  freerange(end, (void*)PHYSTOP);
  // 初始化页面引用数组 
  for(int i=0; i<PGTOL; ++i)  pg_refs[i] = 0;
}

void
freerange(void *pa_start, void *pa_end)
{
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE){
    kfree(p);
  }
}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  // 当页面引用计数仍大于0 则先不释放这个物理页
  acquire(&pg_refs_lock);
  if(--pg_refs[PA2ID((uint64)pa)] > 0){
    release(&pg_refs_lock);
    return;
  }
  release(&pg_refs_lock);

  r = (struct run*)pa;

  // 释放物理页
  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  // 将这个物理页加入空闲页列表
  acquire(&kmem.lock);
  r->next = kmem.freelist;
  kmem.freelist = r;
  release(&kmem.lock);
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc(void)
{
  struct run *r;

  acquire(&kmem.lock);
  r = kmem.freelist;
  if(r){
    kmem.freelist = r->next;
    // 初始化新分配的物理页引用计数
    pg_refs[PA2ID((uint64)r)] = 1;
  }
  release(&kmem.lock);

  if(r) {
    memset((char*)r, 5, PGSIZE); // fill with junk
  }
  return (void*)r;
}

// 添加一个物理页的引用计数
void pg_refs_pp(void* pa) {
  acquire(&pg_refs_lock);
  ++pg_refs[PA2ID((uint64)pa)];
  release(&pg_refs_lock);
}

